package com.zzyl.serve.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.core.domain.BaseEntity;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.serve.domain.AlertData;
import com.zzyl.serve.domain.Device;
import com.zzyl.serve.dto.AlertDataPageDto;
import com.zzyl.serve.dto.HandleAlertDataDto;
import com.zzyl.serve.mapper.AlertDataMapper;
import com.zzyl.serve.mapper.DeviceMapper;
import com.zzyl.serve.mapper.ElderMapper;
import com.zzyl.serve.service.IAlertDataService;
import com.zzyl.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.List;

/**
 * 报警数据Service业务层处理
 *
 * @author liuyp
 * @date 2025-08-26
 */
@Service
public class AlertDataServiceImpl extends ServiceImpl<AlertDataMapper, AlertData> implements IAlertDataService {
    @Autowired
    private AlertDataMapper alertDataMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 查询报警数据
     *
     * @param id 报警数据主键
     * @return 报警数据
     */
    @Override
    public AlertData selectAlertDataById(Long id) {
        return alertDataMapper.selectById(id);
    }

    /**
     * 查询报警数据列表
     *
     * @param dto 报警数据
     * @return 报警数据
     */
    @Override
    public TableDataInfo<AlertData> selectAlertDataList(AlertDataPageDto dto) {

        Long userId = SecurityUtils.getUserId();
        //根据不同的账号能查到不同的数据列表
        LambdaQueryWrapper<AlertData> wrapper = Wrappers.<AlertData>lambdaQuery()
                .eq(AlertData::getUserId,userId)
                .like(StringUtils.isNotEmpty(dto.getDeviceName()), AlertData::getDeviceName, dto.getDeviceName())
                .eq(dto.getStatus() != null, AlertData::getStatus, dto.getStatus())
                .ge(dto.getStartTime() != null, BaseEntity::getCreateTime, dto.getStartTime())
                .le(dto.getEndTime() != null, AlertData::getProcessingTime, dto.getEndTime());
        Page<AlertData> page = page(Page.of(dto.getPageNum(), dto.getPageSize()), wrapper);

/*        List<AlertData> records = page.getRecords();
        int i =0;
        for (AlertData record : records) {
            List<String> nameList = elderMapper.selectName(records.get(i));
            for (String name : nameList) {
                record.setAccessLocation(name);
            }
            i++;
        }*/

        page.getRecords().forEach(alertData -> {
            //设置nickName
//            alertData.setNickname(alertData.getDeviceName());
            //设置带英文的deviceName
            LambdaQueryWrapper<Device> dWrapper = Wrappers.<Device>lambdaQuery().eq(Device::getIotId, alertData.getIotId());
            Device device = deviceMapper.selectOne(dWrapper);
            alertData.setNickname(device.getNodeId());
            if (alertData.getType() == 0) {
                //老人数据异常
                if (alertData.getLocationType() == 0) {
                    //随身设备-手表数据报警
                    List<String> nameList = elderMapper.selectNameById(alertData.getAccessLocation());
                    nameList.forEach(alertData::setAccessLocation);
                } else if (alertData.getLocationType() == 1) {
                    //固定设备-睡眠检测带
                    List<String> nameList = elderMapper.selectNameByBedId(alertData.getAccessLocation());
                    nameList.forEach(alertData::setAccessLocation);
                }
            } else if (alertData.getType() == 1) {
                //设备数据异常-烟雾报警器
                List<String> nameList = elderMapper.selectNameByBedId(alertData.getAccessLocation());
                nameList.forEach(alertData::setAccessLocation);
            }
        });

        TableDataInfo<AlertData> tableDataInfo = new TableDataInfo<>();
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setRows(page.getRecords());
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("请求成功");

        return tableDataInfo;
    }

    /**
     * 新增报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int insertAlertData(AlertData alertData) {
        return alertDataMapper.insert(alertData);
    }

    /**
     * 修改报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int updateAlertData(AlertData alertData) {
        return alertDataMapper.updateById(alertData);
    }

    /**
     * 批量删除报警数据
     *
     * @param ids 需要删除的报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataByIds(Long[] ids) {
        return alertDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除报警数据信息
     *
     * @param id 报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataById(Long id) {
        return alertDataMapper.deleteById(id);
    }

    /**
     * 处理设备报警数据
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleAlertDate(HandleAlertDataDto dto) {
        //接收数据
        AlertData alertData = alertDataMapper.selectById(dto.getId());

        //查询id匹配的数据，修改状态
        alertData.setProcessingResult(dto.getProcessingResult());

        //将0时区的时间变为东八区的时间
        alertData.setProcessingTime(dto.getProcessingTime().atZone(ZoneOffset.UTC).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime());

        //如果设备报警数据处理状态为0，就改为1
        if(alertData.getStatus() == 0){
            alertData.setStatus(1);
        }

        //获取当前登录用户，设置处理人
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        SysUser user = userMapper.selectUserById(userId);
        alertData.setProcessorName(user.getNickName());
        //修改数据库数据
        alertDataMapper.updateAlertData(alertData);

    }
}
